package com.gp.auth;

import java.io.IOException;
// import java.io.IOException;
import java.util.ArrayList;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.JSONObject;
import com.gp.common.result.JsonResult;
import com.gp.common.utils.CookieUtils;
import com.gp.common.utils.StringUtil;
import com.gp.mapper.BaseAccessLogsMapper;
import com.gp.mapper.BasePermissionMapper;
import com.gp.model.entity.AccessLog;
import com.gp.model.entity.BaseUser;

/**
 * @author: 弓成龙
 * @date : 2017年11月26日
 * @email : gcx909109@sina.cn
 * @description: 权限拦截
 */
@Component
public class AuthorizationManager implements HandlerInterceptor {
  // private static final String PROJECT_NAME="/GraduationProject";
  @Autowired
  private BaseAccessLogsMapper accesslogMapper;
  @Autowired
  private BasePermissionMapper permissionMapper;

  @Override
  public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
      throws Exception {

    // 目前根据URL匹配用户可以访问的资源
    // String requestURL = request.getRequestURI();
    // BaseUser user = (BaseUser) CookieUtils.obtainCurrentUser(request);
    // // 2.忽略错误页面
    // if(requestURL.equals(PROJECT_NAME+"/error.html")){ return true;}
    // // 2.如果用户访问的是注册和登录页面则判断用户是否登录，如果用户已经登录的话，禁止用户访问
    // if (requestURL.equals(PROJECT_NAME+"/login") || requestURL.equals(PROJECT_NAME+"/register")
    // || requestURL.equals(PROJECT_NAME+"/outLogin")) {
    // return CookieUtils.obtainCurrentUser(request)==null;
    // }
    // ArrayList<String> userAllPermissionList = getAllUserPermissionInfo(request, user);
    // // 如果用户的权限中存在这个url，则返回true
    // if ((userAllPermissionList != null && userAllPermissionList.contains(requestURL))) {
    // return true;
    // }
    
    
    // 首先进行日志记录
    if (recordAccessLog(request)) {
      // 判断用户身份
      BaseUser user = (BaseUser) CookieUtils.obtainCurrentUser(CookieUtils.getCurrentRequest());
      // 如果是分销商
      if (user==null || (user != null && user.getUserType() == 1)) {
        // 禁止访问管理员界面
        if (request.getRequestURI().contains("/home") && !request.getRequestURI().contains("/home/login.html") && request.getRequestURI().endsWith(".html")) {
          String result = JSONObject.toJSONString(new JsonResult(false, "500", "对不起,您没有权限！"));
          sendResultToClient(response, result);
          return false;
        }
      }
    }
    return true;
  }


  private boolean recordAccessLog(HttpServletRequest request) {
    if (request.getRequestURI().contains("error")
        || StringUtil.isAccessStaticResource(request.getRequestURI())) {
      return true;
    }
    AccessLog entity = CookieUtils.getAccessLog(request);
    return accesslogMapper.insert(entity) == 1;
  }

  /**
   * 将json信息返回桌面
   * 
   * @param response
   * @param result 需要返回的json字符串
   * @throws IOException
   */
  private void sendResultToClient(HttpServletResponse response, String result) throws IOException {
    response.setCharacterEncoding("utf8");
    response.setContentType("application/json;charset=utf8");
    response.setContentLength(result.getBytes().length);
    response.getOutputStream().write(result.getBytes());
    response.getOutputStream().flush();
  }

  /**
   * 用户进行授权使用此方法
   * 
   * @param user 需要进行授权的用户
   * @param request request对象
   */
  public synchronized void doAuthorizateUser(BaseUser user, HttpServletRequest request) {
    ArrayList<String> permissions = permissionMapper.selectUrlByUserID(user.getId());
    HttpSession session = CookieUtils.getSession(request);
    session.setAttribute(CookieUtils.SESSION_PERMISSON_NAME, permissions);
  }

  /**
   * 从全局变量中获取所有用户的权限信息
   * 
   * @param request request对象
   * @return ArrayList<String>
   * 
   *         @SuppressWarnings("unchecked") private ArrayList<String>
   *         getAllUserPermissionInfo(HttpServletRequest request, BaseUser user) { HttpSession
   *         session = CookieUtils.getSession(request); ArrayList<String> userAllPermissionList =
   *         new ArrayList<String>(); if (user != null) { userAllPermissionList =
   *         (ArrayList<String>) session.getAttribute(user.getId().toString()); } return
   *         userAllPermissionList; }
   */

  // 在请求处理之后执行该方法
  @Override
  public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
      ModelAndView modelAndView) throws Exception {}

  // 在请求处理完成所执行的方法
  @Override
  public void afterCompletion(HttpServletRequest request, HttpServletResponse response,
      Object handler, Exception ex) throws Exception {

  }
}

